%% @author Administrator
%% @doc @todo Add description to friend_info.

%%@author wangming
-module(friend_info).
-include("common.hrl").

-export([req_add_friend/4,req_select_friend_room/3,req_del_friend/4]).

%%添加好友
req_add_friend(Aid,TagAid,Sid,Seq)->
	case db:dirty_match(friend_info, #friend_info{aid1=Aid,aid2=TagAid,_='_'}) of
		[]->
			case db:dirty_match(friend_info, #friend_info{aid1=TagAid,aid2=Aid,_='_'}) of
				[]->
					db:insert(#friend_info{aid1=Aid,aid2=TagAid});
				_->skip
			end;
		_->skip
	end.


%%查找好友所在的房间
req_select_friend_room(Aid,Sid,Seq)->
	case db:dirty_get(friend_info,Aid, #friend_info.aid1) of
		FriendList1 when is_list(FriendList1)->
			case db:dirty_get(friend_info,Aid, #friend_info.aid2) of
				FriendList2 when is_list(FriendList2)->
					Fun = fun(#friend_info{aid1=Aid1,aid2=Aid2},Acc)->
								  Acc++[Aid1]++[Aid2]
						  end,
				     case lists:usort(lists:foldl(Fun, [], FriendList1++FriendList2)) of
						 AidList when is_list(AidList) andalso length(AidList) >0 ->
							 Fun1 = fun(TagAid,Acc)->
										   case db:dirty_get(ply,TagAid) of
											   [#ply{room_id=RoomId}|_]->
												   if  RoomId =/= 0->
														   Acc++[{RoomId,TagAid}];
													   true->
														   Acc
												   end;
											   _->Acc
										   end
								   end,
							 lists:foldl(Fun1, [], AidList);
						 _->skip
					 end;
				_->skip
			end;
		_->skip
	end.
					
%%删除好友
req_del_friend(Aid,TagAid,Sid,Seq)->
	case db:dirty_match(friend_info, #friend_info{aid1=Aid,aid2=TagAid,_='_'}) of
		[#friend_info{id=Id}] ->
			db:dirty_del(friend_info, Id);
		_->
			case db:dirty_match(friend_info, #friend_info{aid1=TagAid,aid2=Aid,_='_'}) of
				[#friend_info{id=Id}] ->
					db:dirty_del(friend_info, Id);
				_->skip
			end;
		_->skip
	end.		





